﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Felbot.Interface.Users;
using Felbot.IO;

namespace Felbot.Interface.Conversations {
    /// <summary>
    /// This static class allows you to manage users.
    /// </summary>
    public static class ConversationControl {
        /// <summary>
        /// Gets a conversation from a file.
        /// </summary>
        public static XmlConversation GetConversation(string filePath) {
            XmlControl<XmlConversationRoot> root = new XmlControl<XmlConversationRoot>(filePath);
            return root.Document.Conversation;
        }

        /// <summary>Saves a conversation to a file.</summary>
        /// <param name="conversation">The conversation to save.</param>
        /// <param name="ignoreOld">Ignore the conversation already on file.</param>
        /// <returns>Returns the conversation after saving. Use this to get lines from merged conversations.</returns>
        public static XmlConversation SaveConversation(XmlConversation conversation, bool ignoreOld) {
            XmlConversationRoot root = new XmlConversationRoot();
            root.Version = 1.0;
            root.Conversation = conversation;
            string folderName = root.Conversation.ProfileName;
            string fileName = root.Conversation.Started.ToString("yyyy-MM-dd");
            string filePath = Program.ApplicationFolder + "\\Logs\\" + folderName + "\\" + fileName + ".fbf";

            if (!ignoreOld && File.Exists(filePath)) {
                XmlConversation oldConvo = GetConversation(filePath);
                if (oldConvo != null)
                    root.Conversation.Lines.InsertRange(0, oldConvo.Lines);
            }

            XmlControl<XmlConversationRoot> control = new XmlControl<XmlConversationRoot>(filePath);
            control.Document = root;
            SaveConversation(control);
            return root.Conversation;
        }

        /// <summary>Saves a conversation to a file.</summary>
        public static void SaveConversation(XmlControl<XmlConversationRoot> control) {
            control.Save();
        }
    }
}
